//
//  UAlipay.m
//  UPaySDK
//
//  Created by xu yao on 2021/3/4.
//

#import "UAlipay.h"
#import "EnvironmentDefine.h"
#import "UAlipaySDK.h"
#import "UPaySDK.h"
#import "HCToast.h"
@interface UAlipay ()

@end

static UAlipay *currentHelper = nil;
@implementation UAlipay

+ (void)alipayOrder:(NSString *)alipayUrl {
    if (!currentHelper.schemeStr) {
        LCLog(@"请配置调用支付的app注册在info.plist中的scheme");
        return;
    }
    if (currentHelper.alipayOpenApiClass != NSClassFromString(@"AlipaySDK")) {
        return;
    }
    UAlipaySDK *alipaySDK = [currentHelper.alipayOpenApiClass defaultService];
    [alipaySDK payOrder:alipayUrl fromScheme:currentHelper.schemeStr callback:^(NSDictionary * _Nonnull resultDic) {
        NSInteger orderState = [resultDic[@"resultStatus"] integerValue];
        if (orderState == 9000) {
            //支付成功 回调&通知
            
        }else{
            NSString *returnStr;
            switch (orderState) {
                case 8000:
                    returnStr=@"订单正在处理中";
                    break;
                case 4000:
                    returnStr=@"订单支付失败";
                    break;
                case 6001:
                    returnStr=@"订单取消";
                    break;
                case 6002:
                    returnStr=@"网络连接出错";
                    break;
                    
                default:
                    break;
            }
            // 支付失败 回调&通知
            
        }
    }];
}

+ (void)handleOpenURL:(NSURL *)url onPayResult:(USDKPayResultHandler)payResultHandle {
    if (currentHelper.alipayOpenApiClass != NSClassFromString(@"AlipaySDK")) {
        return;
    }
    UAlipaySDK *alipaySDK = [currentHelper.alipayOpenApiClass defaultService];
    [alipaySDK processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSString *message = resultDic[@"memo"];
        NSString *resultStatus = resultDic[@"resultStatus"];
        if ([resultStatus isEqualToString:@"9000"]) {
            message = @"支付成功";
        }
        [[HCToast shareInstance] showToast:message];
        if (payResultHandle) {
            payResultHandle( USDKPlatformTypeAliPay,[resultStatus isEqualToString:@"9000"] ? UPaySuccess:UPayFail, message);
        }
        if ([resultStatus isEqualToString:@"9000"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UPaySDK closecheckstand];
            });
        }
    }];
}

+ (instancetype)currentHelper {
    if (currentHelper == nil)
        currentHelper = [[UAlipay alloc] init];
    
    return currentHelper;
}


- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

@end
